package com.thesis.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * 
 * @author n.d
 *Use of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day. 
 *(User of Google Maps API for Business may perform up to 100,000 requests per day.) 
 *This limit is enforced to prevent abuse and/or repurposing of the Geocoding API, 
 *and this limit may be changed in the future without notice. 
 *Additionally, we enforce a request rate limit to prevent abuse of the service. 
 *If you exceed the 24-hour limit or otherwise abuse the service, 
 *the Geocoding API may stop working for you temporarily. 
 *If you continue to exceed this limit, your access to the Geocoding API may be blocked.
 *
 *
 *
 *SENSOR
 *http://webapps.stackexchange.com/questions/13163/why-is-google-maps-enforcing-the-sensor-parameter
 */

public class ReverseGeocoding {

	double m_lng, m_lat;
	String m_baseuri;
	
	public ReverseGeocoding()
	{
		
	}
	
	public ReverseGeocoding(double lat, double lng)
	{
		m_lng=lng;
		m_lat=lat;
		m_baseuri = "http://maps.googleapis.com/maps/api/geocode/xml?latlng=" 
				+ Double.toString(m_lat) +","+ Double.toString(m_lng) 
				+ "&sensor=false";
	}
	
	public void setLatLng(double lat, double lng)
	{
		m_lng=lng;
		m_lat=lat;
		m_baseuri = "http://maps.googleapis.com/maps/api/geocode/xml?latlng=" 
				+ Double.toString(m_lat) +","+ Double.toString(m_lng) 
				+ "&sensor=false";
	}
	
	public String lookup()
	{
		try {
			URLConnection gmapconnection;
			URL gmap = new URL(m_baseuri);

			gmapconnection = gmap.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					gmapconnection.getInputStream()));
			String inputLine;
			while ((inputLine = in.readLine()) != null)
			{	
				if (inputLine.contains("formatted_address"))
				{
					//inputLine = in.readLine();
					in.close();
					inputLine = inputLine.replace("<formatted_address>", "");
					inputLine = inputLine.replace("</formatted_address>", "");
					return inputLine;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.getMessage();
		}
		return "DONE WITH ERROR: " + m_baseuri;
	}
}
